import sys
import os
import json
import math
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, 
                            QHBoxLayout, QListWidget, QPushButton, QFileDialog, 
                            QLabel, QSlider, QStyle, QListWidgetItem, QMessageBox,
                            QTabWidget, QSplitter, QSystemTrayIcon, QMenu, QAction)
from PyQt5.QtCore import QUrl, Qt, QTimer, QPoint, QRect, QSize, pyqtSignal
from PyQt5.QtGui import (QIcon, QFont, QColor, QPalette, QBrush, QPixmap, 
                         QPainter, QRadialGradient, QConicalGradient, QPen,
                         QImage, QLinearGradient)

# 确保中文显示正常
font_families = ["SimHei", "WenQuanYi Micro Hei", "Heiti TC", "Arial Unicode MS"]

class CDVisualizer(QLabel):
    """碟片可视化组件，实现播放时的旋转效果"""
    def __init__(self, parent=None):
        super().__init__(parent)
        self.angle = 0
        self.is_playing = False
        self.album_art = None
        
        # 初始化定时器用于旋转动画
        self.rotation_timer = QTimer(self)
        self.rotation_timer.timeout.connect(self.update_rotation)
        self.rotation_timer.start(50)  # 每50ms更新一次旋转角度
        
        # 设置大小
        self.setMinimumSize(200, 200)
        self.setMaximumSize(300, 300)
        
    def set_playing(self, playing):
        """设置播放状态，控制旋转动画"""
        self.is_playing = playing
        
    def set_album_art(self, image_path=None):
        """设置专辑封面（这里简化处理，实际可从音频文件读取）"""
        if image_path and os.path.exists(image_path):
            self.album_art = QPixmap(image_path).scaled(
                self.width()-20, self.height()-20, 
                Qt.KeepAspectRatio, Qt.SmoothTransformation
            )
        else:
            self.album_art = None
        self.update()
        
    def update_rotation(self):
        """更新旋转角度"""
        if self.is_playing:
            self.angle = (self.angle + 1) % 360
            self.update()
            
    def paintEvent(self, event):
        """绘制旋转的碟片效果"""
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        
        # 获取绘制区域
        size = min(self.width(), self.height())
        rect = QRect((self.width() - size) // 2, (self.height() - size) // 2, size, size)
        painter.translate(rect.center())  # 移动原点到中心
        
        # 如果正在播放，应用旋转
        if self.is_playing:
            painter.rotate(self.angle)
        
        # 绘制碟片外框
        outer_radius = size // 2
        inner_radius = outer_radius // 5
        
        # 碟片渐变效果
        gradient = QConicalGradient(QPoint(0, 0), 0)
        gradient.setColorAt(0.0, QColor(40, 40, 40))
        gradient.setColorAt(0.25, QColor(60, 60, 60))
        gradient.setColorAt(0.5, QColor(50, 50, 50))
        gradient.setColorAt(0.75, QColor(70, 70, 70))
        gradient.setColorAt(1.0, QColor(40, 40, 40))
        
        painter.setBrush(QBrush(gradient))
        painter.setPen(QPen(QColor(100, 100, 100), 2))
        painter.drawEllipse(QPoint(0, 0), outer_radius, outer_radius)
        
        # 绘制专辑封面（如果有）
        if self.album_art:
            art_radius = outer_radius * 0.7
            painter.drawPixmap(
                -art_radius, -art_radius, 
                art_radius * 2, art_radius * 2, 
                self.album_art
            )
        
        # 绘制中心圆点
        center_gradient = QRadialGradient(0, 0, inner_radius)
        center_gradient.setColorAt(0, QColor(80, 80, 80))
        center_gradient.setColorAt(1, QColor(40, 40, 40))
        
        painter.setBrush(QBrush(center_gradient))
        painter.setPen(QPen(QColor(120, 120, 120), 1))
        painter.drawEllipse(QPoint(0, 0), inner_radius, inner_radius)
        
        # 绘制碟片纹路
        painter.setPen(QPen(QColor(70, 70, 70, 100), 1))
        for i in range(12):
            painter.drawLine(inner_radius, 0, outer_radius, 0)
            painter.rotate(30)  # 每30度绘制一条线


class MiniPlayer(QMainWindow):
    """迷你播放器窗口"""
    show_main_window = pyqtSignal()
    
    def __init__(self, player_instance):
        super().__init__()
        self.main_player = player_instance
        self.init_ui()
        
    def init_ui(self):
        self.setWindowTitle("迷你播放器")
        self.setFixedSize(300, 120)
        self.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint)
        
        # 设置样式
        self.setStyleSheet("""
            QMainWindow {
                background-color: #1a1a2e;
                border: 2px solid #0f3460;
                border-radius: 10px;
            }
            QLabel {
                color: #eaeaea;
                font-family: SimHei;
            }
            QPushButton {
                background-color: #16213e;
                color: #eaeaea;
                border-radius: 8px;
                border: none;
                font-size: 9pt;
            }
            QPushButton:hover {
                background-color: #0f3460;
            }
        """)
        
        # 主布局
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        layout = QVBoxLayout(central_widget)
        layout.setContentsMargins(10, 5, 10, 5)
        layout.setSpacing(5)
        
        # 顶部：歌曲信息和关闭按钮
        top_layout = QHBoxLayout()
        
        self.song_label = QLabel("未播放")
        self.song_label.setFont(QFont("SimHei", 9))
        self.song_label.setStyleSheet("color: #eaeaea;")
        top_layout.addWidget(self.song_label)
        
        self.expand_btn = QPushButton("展开")
        self.expand_btn.setFixedSize(40, 20)
        self.expand_btn.clicked.connect(self.show_main_window.emit)
        top_layout.addWidget(self.expand_btn)
        
        self.close_btn = QPushButton("×")
        self.close_btn.setFixedSize(20, 20)
        self.close_btn.setStyleSheet("color: #ff6b6b; font-weight: bold;")
        self.close_btn.clicked.connect(self.hide)
        top_layout.addWidget(self.close_btn)
        
        layout.addLayout(top_layout)
        
        # 中部：进度条
        self.mini_progress = QSlider(Qt.Horizontal)
        self.mini_progress.setFixedHeight(15)
        self.mini_progress.setStyleSheet("""
            QSlider::groove:horizontal {
                border: 1px solid #0f3460;
                background: #16213e;
                height: 4px;
                border-radius: 2px;
            }
            QSlider::handle:horizontal {
                background: #e94560;
                border: 1px solid #e94560;
                width: 12px;
                margin: -4px 0;
                border-radius: 6px;
            }
        """)
        layout.addWidget(self.mini_progress)
        
        # 底部：控制按钮
        control_layout = QHBoxLayout()
        control_layout.setSpacing(8)
        
        self.mini_prev_btn = QPushButton("⏮")
        self.mini_prev_btn.setFixedSize(30, 30)
        self.mini_prev_btn.clicked.connect(self.main_player.play_previous)
        control_layout.addWidget(self.mini_prev_btn)
        
        self.mini_play_btn = QPushButton("▶")
        self.mini_play_btn.setFixedSize(35, 35)
        self.mini_play_btn.setStyleSheet("QPushButton { font-size: 12pt; background-color: #e94560; } QPushButton:hover { background-color: #ff2e63; }")
        self.mini_play_btn.clicked.connect(self.main_player.toggle_play_pause)
        control_layout.addWidget(self.mini_play_btn)
        
        self.mini_next_btn = QPushButton("⏭")
        self.mini_next_btn.setFixedSize(30, 30)
        self.mini_next_btn.clicked.connect(self.main_player.play_next)
        control_layout.addWidget(self.mini_next_btn)
        
        # 音量滑块
        self.mini_volume = QSlider(Qt.Horizontal)
        self.mini_volume.setFixedWidth(60)
        self.mini_volume.setFixedHeight(20)
        self.mini_volume.setValue(80)
        self.mini_volume.valueChanged.connect(self.main_player.set_volume)
        self.mini_volume.setStyleSheet("""
            QSlider::groove:horizontal {
                border: 1px solid #0f3460;
                background: #16213e;
                height: 3px;
                border-radius: 1px;
            }
            QSlider::handle:horizontal {
                background: #e94560;
                border: 1px solid #e94560;
                width: 10px;
                margin: -3px 0;
                border-radius: 5px;
            }
        """)
        control_layout.addWidget(self.mini_volume)
        
        layout.addLayout(control_layout)
        
    def update_song_info(self, song_name):
        """更新歌曲信息"""
        if len(song_name) > 25:
            song_name = song_name[:22] + "..."
        self.song_label.setText(song_name)
        
    def update_play_button(self, is_playing):
        """更新播放按钮状态"""
        if is_playing:
            self.mini_play_btn.setText("⏸")
        else:
            self.mini_play_btn.setText("▶")
            
    def update_progress(self, position, duration):
        """更新进度条"""
        if duration > 0:
            self.mini_progress.setMaximum(duration)
            self.mini_progress.setValue(position)
            
    def mousePressEvent(self, event):
        """实现窗口拖拽"""
        if event.button() == Qt.LeftButton:
            self.drag_start_position = event.globalPos() - self.frameGeometry().topLeft()
            event.accept()
            
    def mouseMoveEvent(self, event):
        """实现窗口拖拽"""
        if event.buttons() == Qt.LeftButton and hasattr(self, 'drag_start_position'):
            self.move(event.globalPos() - self.drag_start_position)
            event.accept()


class MusicPlayer(QMainWindow):
    def __init__(self):
        super().__init__()
        
        # 配置文件路径
        self.config_path = os.path.join(os.path.expanduser("~"), ".modern_music_player")
        self.playlist_file = os.path.join(self.config_path, "playlist.json")
        self.play_history_file = os.path.join(self.config_path, "play_history.json")
        
        # 初始化播放列表和历史记录
        self.playlist = []
        self.play_history = []
        self.current_index = -1
        self.max_history = 50  # 最大历史记录数量
        
        # 创建配置目录
        if not os.path.exists(self.config_path):
            os.makedirs(self.config_path)
        
        # 初始化媒体播放器
        self.player = None
        self.init_player()
        
        # 加载保存的播放列表和历史记录
        self.load_playlist()
        self.load_play_history()
        
        # 初始化UI
        self.init_ui()
        
        # 创建系统托盘
        self.init_tray()
        
        # 创建迷你播放器
        self.mini_player = MiniPlayer(self)
        self.mini_player.show_main_window.connect(self.show_main_window)
        
        # 创建定时器更新进度
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.update_progress)
        self.timer.start(1000)  # 1秒更新一次

    def init_player(self):
        """初始化媒体播放器"""
        from PyQt5.QtMultimedia import QMediaPlayer
        self.player = QMediaPlayer(None, QMediaPlayer.LowLatency)
        self.player.positionChanged.connect(self.update_position)
        self.player.durationChanged.connect(self.update_duration)
        self.player.stateChanged.connect(self.state_changed)
        self.player.mediaStatusChanged.connect(self.media_status_changed)

    def init_tray(self):
        """初始化系统托盘"""
        # 检查系统是否支持托盘
        if not QSystemTrayIcon.isSystemTrayAvailable():
            QMessageBox.critical(self, "系统托盘", "系统不支持托盘功能")
            return
            
        # 创建托盘图标
        self.tray_icon = QSystemTrayIcon(self)
        
        # 设置托盘图标（使用系统默认的音频图标）
        tray_icon = self.style().standardIcon(QStyle.SP_MediaVolume)
        self.tray_icon.setIcon(tray_icon)
        
        # 创建托盘菜单
        tray_menu = QMenu()
        
        # 显示主窗口
        show_action = QAction("显示主窗口", self)
        show_action.triggered.connect(self.show_main_window)
        tray_menu.addAction(show_action)
        
        # 显示迷你播放器
        mini_action = QAction("迷你播放器", self)
        mini_action.triggered.connect(self.show_mini_player)
        tray_menu.addAction(mini_action)
        
        tray_menu.addSeparator()
        
        # 播放控制
        play_action = QAction("播放/暂停", self)
        play_action.triggered.connect(self.toggle_play_pause)
        tray_menu.addAction(play_action)
        
        prev_action = QAction("上一首", self)
        prev_action.triggered.connect(self.play_previous)
        tray_menu.addAction(prev_action)
        
        next_action = QAction("下一首", self)
        next_action.triggered.connect(self.play_next)
        tray_menu.addAction(next_action)
        
        tray_menu.addSeparator()
        
        # 退出
        quit_action = QAction("退出", self)
        quit_action.triggered.connect(self.quit_application)
        tray_menu.addAction(quit_action)
        
        self.tray_icon.setContextMenu(tray_menu)
        
        # 托盘双击事件
        self.tray_icon.activated.connect(self.tray_icon_activated)
        
        # 显示托盘图标
        self.tray_icon.show()
        
        # 显示托盘消息
        self.tray_icon.showMessage(
            "音乐播放器",
            "播放器已最小化到系统托盘",
            QSystemTrayIcon.Information,
            2000
        )
        
    def tray_icon_activated(self, reason):
        """托盘图标点击事件"""
        if reason == QSystemTrayIcon.DoubleClick:
            self.show_main_window()
            
    def show_main_window(self):
        """显示主窗口"""
        self.show()
        self.raise_()
        self.activateWindow()
        self.mini_player.hide()
        
    def show_mini_player(self):
        """显示迷你播放器"""
        self.hide()
        self.mini_player.show()
        self.mini_player.raise_()
        self.mini_player.activateWindow()
        
    def hide_to_tray(self):
        """最小化到托盘"""
        self.hide()
        self.mini_player.show()
        self.tray_icon.showMessage(
            "音乐播放器",
            "播放器已切换到迷你模式",
            QSystemTrayIcon.Information,
            1500
        )
        
    def quit_application(self):
        """完全退出应用程序"""
        # 保存数据
        self.save_playlist()
        self.save_play_history()
        
        # 隐藏托盘图标
        self.tray_icon.hide()
        
        # 关闭所有窗口
        self.mini_player.close()
        
        # 退出应用
        QApplication.quit()

    def init_ui(self):
        # 设置窗口
        self.setWindowTitle("旋律 - 音乐播放器")
        self.setGeometry(200, 200, 1000, 700)
        self.setMinimumSize(800, 600)
        
        # 设置全局样式（移除不支持的transition和transform属性）
        self.setStyleSheet("""
            /* 全局样式 */
            QMainWindow, QWidget {
                background-color: #1a1a2e;
                color: #eaeaea;
            }
            
            /* 标签样式 */
            QLabel {
                color: #eaeaea;
                font-family: %s;
            }
            
            /* 按钮样式 */
            QPushButton {
                background-color: #16213e;
                color: #eaeaea;
                border-radius: 15px;
                padding: 8px 16px;
                border: none;
                font-family: %s;
                font-size: 10pt;
            }
            QPushButton:hover {
                background-color: #0f3460;
            }
            QPushButton:pressed {
                background-color: #0a2540;
            }
            
            /* 列表样式 */
            QListWidget {
                background-color: #16213e;
                border: 1px solid #0f3460;
                border-radius: 8px;
                padding: 5px;
                font-family: %s;
                font-size: 10pt;
                color: #eaeaea;
                alternate-background-color: #1a2744;
            }
            QListWidget::item {
                padding: 5px;
                border-radius: 4px;
            }
            QListWidget::item:selected {
                background-color: #0f3460;
                color: white;
            }
            QListWidget::item:hover {
                background-color: #1a2744;
            }
            
            /* 滑块样式 */
            QSlider::groove:horizontal {
                border: 1px solid #0f3460;
                background: #16213e;
                height: 6px;
                border-radius: 3px;
            }
            QSlider::handle:horizontal {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #e94560, stop:1 #ff2e63);
                border: 1px solid #e94560;
                width: 20px;
                margin: -7px 0;
                border-radius: 10px;
            }
            QSlider::handle:horizontal:hover {
                width: 22px;
                margin: -8px 0;
            }
            
            /* 标签页样式 */
            QTabWidget::pane {
                border: 1px solid #0f3460;
                border-radius: 8px;
                background-color: #16213e;
            }
            QTabBar::tab {
                background-color: #16213e;
                color: #eaeaea;
                padding: 8px 16px;
                border-radius: 6px 6px 0 0;
                margin-right: 2px;
                font-family: %s;
            }
            QTabBar::tab:selected {
                background-color: #0f3460;
                border-bottom-color: #0f3460;
            }
            QTabBar::tab:hover:!selected {
                background-color: #1a2744;
            }
            
            /* 分隔器样式 */
            QSplitter::handle {
                background-color: #0f3460;
            }
            QSplitter::handle:hover {
                background-color: #e94560;
            }
        """ % (font_families[0], font_families[0], font_families[0], font_families[0]))
        
        # 主部件和布局
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        main_layout = QHBoxLayout(central_widget)
        main_layout.setContentsMargins(15, 15, 15, 15)
        main_layout.setSpacing(15)
        
        # 创建左右分隔器
        splitter = QSplitter(Qt.Horizontal)
        main_layout.addWidget(splitter)
        
        # 左侧面板 - 播放列表和历史记录
        left_panel = QWidget()
        left_layout = QVBoxLayout(left_panel)
        left_layout.setContentsMargins(5, 5, 5, 5)
        left_layout.setSpacing(10)
        
        # 左侧标题
        left_title = QLabel("音乐库")
        left_title.setFont(QFont(font_families[0], 14, QFont.Bold))
        left_title.setStyleSheet("color: #e94560; padding: 5px 0;")
        left_layout.addWidget(left_title)
        
        # 标签页 - 播放列表和历史记录
        self.tab_widget = QTabWidget()
        left_layout.addWidget(self.tab_widget)
        
        # 播放列表标签页
        playlist_tab = QWidget()
        playlist_layout = QVBoxLayout(playlist_tab)
        playlist_layout.setContentsMargins(5, 5, 5, 5)
        
        # 播放列表
        self.playlist_widget = QListWidget()
        self.playlist_widget.setAlternatingRowColors(True)
        self.playlist_widget.itemDoubleClicked.connect(self.play_selected)
        playlist_layout.addWidget(self.playlist_widget)
        
        # 播放列表按钮
        playlist_buttons = QHBoxLayout()
        
        self.add_btn = QPushButton("添加音乐")
        self.add_btn.setIcon(self.style().standardIcon(getattr(QStyle, "SP_DialogOpenButton")))
        self.add_btn.clicked.connect(self.add_music)
        playlist_buttons.addWidget(self.add_btn)
        
        self.remove_btn = QPushButton("删除选中")
        self.remove_btn.setIcon(self.style().standardIcon(getattr(QStyle, "SP_DialogDiscardButton")))
        self.remove_btn.clicked.connect(self.remove_music)
        playlist_buttons.addWidget(self.remove_btn)
        
        playlist_layout.addLayout(playlist_buttons)
        self.tab_widget.addTab(playlist_tab, "播放列表")
        
        # 历史记录标签页
        history_tab = QWidget()
        history_layout = QVBoxLayout(history_tab)
        history_layout.setContentsMargins(5, 5, 5, 5)
        
        self.history_widget = QListWidget()
        self.history_widget.setAlternatingRowColors(True)
        self.history_widget.itemDoubleClicked.connect(self.play_from_history)
        history_layout.addWidget(self.history_widget)
        
        self.clear_history_btn = QPushButton("清除历史")
        self.clear_history_btn.clicked.connect(self.clear_play_history)
        history_layout.addWidget(self.clear_history_btn)
        
        self.tab_widget.addTab(history_tab, "播放历史")
        
        # 添加左侧面板到分隔器
        splitter.addWidget(left_panel)
        
        # 右侧面板 - 播放控制和可视化
        right_panel = QWidget()
        right_layout = QVBoxLayout(right_panel)
        right_layout.setContentsMargins(5, 5, 5, 5)
        right_layout.setSpacing(20)
        
        # 右侧标题
        right_title = QLabel("正在播放")
        right_title.setFont(QFont(font_families[0], 14, QFont.Bold))
        right_title.setStyleSheet("color: #e94560; padding: 5px 0;")
        right_title.setAlignment(Qt.AlignCenter)
        right_layout.addWidget(right_title)
        
        # 碟片可视化组件
        self.cd_visualizer = CDVisualizer()
        self.cd_visualizer.setAlignment(Qt.AlignCenter)
        right_layout.addWidget(self.cd_visualizer)
        
        # 当前播放歌曲标签
        self.current_song_label = QLabel("未播放任何歌曲")
        self.current_song_label.setFont(QFont(font_families[0], 12))
        self.current_song_label.setAlignment(Qt.AlignCenter)
        self.current_song_label.setStyleSheet("color: #eaeaea; padding: 10px; border-radius: 8px; background-color: #16213e;")
        self.current_song_label.setWordWrap(True)
        right_layout.addWidget(self.current_song_label)
        
        # 进度条布局
        progress_container = QWidget()
        progress_container.setStyleSheet("background-color: #16213e; border-radius: 8px; padding: 10px;")
        progress_layout = QVBoxLayout(progress_container)
        
        self.progress_label = QLabel("00:00 / 00:00")
        self.progress_label.setFont(QFont(font_families[0], 10))
        self.progress_label.setAlignment(Qt.AlignCenter)
        progress_layout.addWidget(self.progress_label)
        
        self.progress_bar = QSlider(Qt.Horizontal)
        self.progress_bar.sliderMoved.connect(self.set_position)
        progress_layout.addWidget(self.progress_bar)
        
        right_layout.addWidget(progress_container)
        
        # 控制按钮布局
        control_container = QWidget()
        control_container.setStyleSheet("background-color: #16213e; border-radius: 8px; padding: 15px;")
        control_layout = QVBoxLayout(control_container)
        
        # 主要控制按钮
        main_controls = QHBoxLayout()
        main_controls.setSpacing(15)
        main_controls.setAlignment(Qt.AlignCenter)  # 水平居中
        
        self.prev_btn = QPushButton()
        self.prev_btn.setIcon(self.style().standardIcon(getattr(QStyle, "SP_MediaSkipBackward")))
        self.prev_btn.setIconSize(QSize(32, 32))
        self.prev_btn.setMinimumSize(40, 40)
        self.prev_btn.clicked.connect(self.play_previous)
        main_controls.addWidget(self.prev_btn)
        
        self.play_btn = QPushButton()
        self.play_btn.setIcon(self.style().standardIcon(getattr(QStyle, "SP_MediaPlay")))
        self.play_btn.setIconSize(QSize(48, 48))
        self.play_btn.setMinimumSize(60, 60)
        self.play_btn.clicked.connect(self.toggle_play_pause)
        main_controls.addWidget(self.play_btn)
        
        self.stop_btn = QPushButton()
        self.stop_btn.setIcon(self.style().standardIcon(getattr(QStyle, "SP_MediaStop")))
        self.stop_btn.setIconSize(QSize(32, 32))
        self.stop_btn.setMinimumSize(40, 40)
        self.stop_btn.clicked.connect(self.stop_playback)
        main_controls.addWidget(self.stop_btn)
        
        self.next_btn = QPushButton()
        self.next_btn.setIcon(self.style().standardIcon(getattr(QStyle, "SP_MediaSkipForward")))
        self.next_btn.setIconSize(QSize(32, 32))
        self.next_btn.setMinimumSize(40, 40)
        self.next_btn.clicked.connect(self.play_next)
        main_controls.addWidget(self.next_btn)
        
        control_layout.addLayout(main_controls)
        
        # 音量控制（修复居中问题）
        volume_layout = QHBoxLayout()
        volume_layout.setSpacing(10)
        volume_layout.setAlignment(Qt.AlignCenter)  # 水平居中
        
        volume_label = QLabel("音量:")
        volume_label.setFont(QFont(font_families[0], 10))
        volume_layout.addWidget(volume_label)
        
        self.volume_slider = QSlider(Qt.Horizontal)
        self.volume_slider.setMaximumWidth(150)
        self.volume_slider.setValue(80)
        self.volume_slider.valueChanged.connect(self.set_volume)
        self.player.setVolume(80)
        volume_layout.addWidget(self.volume_slider)
        
        # 使用布局的对齐方式代替widget的setAlignment
        control_layout.addLayout(volume_layout)
        
        right_layout.addWidget(control_container)
        
        # 添加右侧面板到分隔器
        splitter.addWidget(right_panel)
        
        # 设置分隔器初始大小
        splitter.setSizes([350, 600])
        
        # 更新播放列表和历史记录显示
        self.update_playlist_display()
        self.update_history_display()

    def add_music(self):
        files, _ = QFileDialog.getOpenFileNames(
            self, "选择音乐文件", 
            os.path.expanduser("~"), 
            "音频文件 (*.mp3 *.wav *.ogg *.flac *.m4a)"
        )
        
        if files:
            new_songs = 0
            for file in files:
                if file not in self.playlist:
                    self.playlist.append(file)
                    new_songs += 1
            
            if new_songs > 0:
                self.update_playlist_display()
                self.save_playlist()
                QMessageBox.information(self, "添加成功", f"成功添加 {new_songs} 首音乐")

    def remove_music(self):
        selected_items = self.playlist_widget.selectedItems()
        if not selected_items:
            QMessageBox.warning(self, "警告", "请先选择要删除的音乐")
            return
            
        # 获取选中的索引
        indices = sorted([self.playlist_widget.row(item) for item in selected_items], reverse=True)
        
        # 删除选中的项目
        for index in indices:
            del self.playlist[index]
            # 如果删除的是当前播放的歌曲，停止播放
            if index == self.current_index:
                self.stop_playback()
                self.current_index = -1
        
        self.update_playlist_display()
        self.save_playlist()
        QMessageBox.information(self, "删除成功", f"已删除 {len(selected_items)} 首音乐")

    def update_playlist_display(self):
        self.playlist_widget.clear()
        for file in self.playlist:
            # 只显示文件名，不显示完整路径
            filename = os.path.basename(file)
            item = QListWidgetItem(filename)
            item.setToolTip(file)  # 鼠标悬停时显示完整路径
            self.playlist_widget.addItem(item)
        
        # 高亮显示当前播放的歌曲
        if 0 <= self.current_index < len(self.playlist):
            self.playlist_widget.setCurrentRow(self.current_index)
            item = self.playlist_widget.item(self.current_index)
            if item:
                item.setBackground(QColor("#0f3460"))

    def play_selected(self):
        selected_index = self.playlist_widget.currentRow()
        if selected_index >= 0 and selected_index < len(self.playlist):
            self.current_index = selected_index
            self.play_current()
            # 添加到播放历史
            self.add_to_play_history(self.playlist[selected_index])

    def play_from_history(self):
        selected_index = self.history_widget.currentRow()
        if selected_index >= 0 and selected_index < len(self.play_history):
            song_path = self.play_history[selected_index]
            # 检查是否在播放列表中
            if song_path in self.playlist:
                self.current_index = self.playlist.index(song_path)
            else:
                # 如果不在播放列表中，添加进去
                self.playlist.append(song_path)
                self.current_index = len(self.playlist) - 1
                self.save_playlist()
                self.update_playlist_display()
                
            self.play_current()
            # 重新添加到历史记录（更新顺序）
            self.add_to_play_history(song_path)

    def play_current(self):
        if 0 <= self.current_index < len(self.playlist):
            song_path = self.playlist[self.current_index]
            try:
                # 加载并播放音乐
                from PyQt5.QtMultimedia import QMediaContent
                self.player.setMedia(QMediaContent(QUrl.fromLocalFile(song_path)))
                self.player.play()
                
                # 更新碟片动画状态
                self.cd_visualizer.set_playing(True)
                
                # 尝试从歌曲文件获取专辑封面（这里简化处理）
                self.cd_visualizer.set_album_art()  # 实际应用中可传入专辑封面路径
                
                # 更新当前播放歌曲标签
                song_name = os.path.basename(song_path)
                self.current_song_label.setText(f"正在播放: {song_name}")
                
                # 更新迷你播放器信息
                self.mini_player.update_song_info(song_name)
                
                # 更新播放列表显示（高亮当前歌曲）
                self.update_playlist_display()
                
            except Exception as e:
                QMessageBox.critical(self, "播放错误", f"无法播放 {song_path}:\n{str(e)}")

    def toggle_play_pause(self):
        if not self.playlist:
            QMessageBox.information(self, "提示", "请先添加音乐到播放列表")
            return
            
        from PyQt5.QtMultimedia import QMediaPlayer
        if self.player.state() == QMediaPlayer.PlayingState:
            self.player.pause()
            self.cd_visualizer.set_playing(False)
        else:
            if self.player.mediaStatus() == QMediaPlayer.NoMedia and self.playlist:
                # 如果没有加载媒体，从第一首开始播放
                self.current_index = 0
                self.play_current()
                self.add_to_play_history(self.playlist[self.current_index])
            else:
                self.player.play()
                self.cd_visualizer.set_playing(True)

    def stop_playback(self):
        self.player.stop()
        self.cd_visualizer.set_playing(False)
        self.progress_bar.setValue(0)
        self.progress_label.setText("00:00 / 00:00")

    def play_next(self):
        if not self.playlist:
            return
            
        self.current_index = (self.current_index + 1) % len(self.playlist)
        self.play_current()
        self.add_to_play_history(self.playlist[self.current_index])

    def play_previous(self):
        if not self.playlist:
            return
            
        self.current_index = (self.current_index - 1) % len(self.playlist)
        if self.current_index < 0:
            self.current_index = len(self.playlist) - 1
        self.play_current()
        self.add_to_play_history(self.playlist[self.current_index])

    def set_volume(self, value):
        self.player.setVolume(value)

    def set_position(self, position):
        self.player.setPosition(position)

    def update_position(self, position):
        # 防止滑块更新时触发不必要的事件
        self.progress_bar.blockSignals(True)
        self.progress_bar.setValue(position)
        self.progress_bar.blockSignals(False)
        
        # 更新迷你播放器进度条
        self.mini_player.update_progress(position, self.player.duration())
        
        # 更新时间标签
        current_time = self.format_time(position // 1000)
        total_time = self.format_time(self.player.duration() // 1000)
        self.progress_label.setText(f"{current_time} / {total_time}")

    def update_duration(self, duration):
        self.progress_bar.setMaximum(duration)
        # 更新时间标签
        current_time = self.format_time(self.player.position() // 1000)
        total_time = self.format_time(duration // 1000)
        self.progress_label.setText(f"{current_time} / {total_time}")

    def update_progress(self):
        # 定期更新进度（作为辅助，主要依赖positionChanged信号）
        pass

    def state_changed(self, state):
        from PyQt5.QtMultimedia import QMediaPlayer
        if state == QMediaPlayer.PlayingState:
            self.play_btn.setIcon(self.style().standardIcon(getattr(QStyle, "SP_MediaPause")))
            self.cd_visualizer.set_playing(True)
            self.mini_player.update_play_button(True)
        else:
            self.play_btn.setIcon(self.style().standardIcon(getattr(QStyle, "SP_MediaPlay")))
            self.mini_player.update_play_button(False)
            if state == QMediaPlayer.StoppedState:
                self.cd_visualizer.set_playing(False)

    def media_status_changed(self, status):
        from PyQt5.QtMultimedia import QMediaPlayer
        # 当当前媒体播放完毕，自动播放下一首
        if status == QMediaPlayer.EndOfMedia:
            self.play_next()

    def format_time(self, seconds):
        minutes = int(seconds // 60)
        seconds = int(seconds % 60)
        return f"{minutes:02d}:{seconds:02d}"

    def save_playlist(self):
        try:
            with open(self.playlist_file, 'w', encoding='utf-8') as f:
                json.dump(self.playlist, f, ensure_ascii=False)
        except Exception as e:
            QMessageBox.warning(self, "保存失败", f"无法保存播放列表:\n{str(e)}")

    def load_playlist(self):
        try:
            if os.path.exists(self.playlist_file):
                with open(self.playlist_file, 'r', encoding='utf-8') as f:
                    self.playlist = json.load(f)
                    
                # 过滤不存在的文件
                valid_playlist = []
                for file in self.playlist:
                    if os.path.exists(file):
                        valid_playlist.append(file)
                
                if len(valid_playlist) < len(self.playlist):
                    self.playlist = valid_playlist
                    self.save_playlist()  # 保存过滤后的播放列表
        except Exception as e:
            QMessageBox.warning(self, "加载失败", f"无法加载播放列表:\n{str(e)}")
            self.playlist = []

    # 播放历史相关功能
    def add_to_play_history(self, song_path):
        """添加歌曲到播放历史"""
        # 如果已经存在，先移除
        if song_path in self.play_history:
            self.play_history.remove(song_path)
        # 添加到开头
        self.play_history.insert(0, song_path)
        # 限制历史记录数量
        if len(self.play_history) > self.max_history:
            self.play_history = self.play_history[:self.max_history]
        # 保存并更新显示
        self.save_play_history()
        self.update_history_display()

    def update_history_display(self):
        """更新历史记录显示"""
        self.history_widget.clear()
        for file in self.play_history:
            filename = os.path.basename(file)
            item = QListWidgetItem(filename)
            item.setToolTip(file)  # 鼠标悬停时显示完整路径
            self.history_widget.addItem(item)

    def save_play_history(self):
        """保存播放历史"""
        try:
            with open(self.play_history_file, 'w', encoding='utf-8') as f:
                json.dump(self.play_history, f, ensure_ascii=False)
        except Exception as e:
            QMessageBox.warning(self, "保存失败", f"无法保存播放历史:\n{str(e)}")

    def load_play_history(self):
        """加载播放历史"""
        try:
            if os.path.exists(self.play_history_file):
                with open(self.play_history_file, 'r', encoding='utf-8') as f:
                    self.play_history = json.load(f)
                    
                # 过滤不存在的文件
                valid_history = []
                for file in self.play_history:
                    if os.path.exists(file):
                        valid_history.append(file)
                
                self.play_history = valid_history
        except Exception as e:
            QMessageBox.warning(self, "加载失败", f"无法加载播放历史:\n{str(e)}")
            self.play_history = []

    def clear_play_history(self):
        """清除播放历史"""
        reply = QMessageBox.question(
            self, "确认清除", "确定要清除所有播放历史吗？",
            QMessageBox.Yes | QMessageBox.No, QMessageBox.No
        )
        if reply == QMessageBox.Yes:
            self.play_history = []
            self.save_play_history()
            self.update_history_display()

    def closeEvent(self, event):
        """重写关闭事件，最小化到托盘而不是退出"""
        if self.tray_icon.isVisible():
            # 最小化到托盘
            self.hide_to_tray()
            event.ignore()  # 忽略关闭事件
        else:
            # 如果托盘不可用，正常退出
            self.quit_application()
            event.accept()


if __name__ == "__main__":
    app = QApplication(sys.argv)
    # 设置应用字体
    font = QFont()
    font.setFamily(font_families[0])
    app.setFont(font)
    player = MusicPlayer()
    player.show()
    sys.exit(app.exec_())
